/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author SuperMeng
 */
public class server {

    public static final int serverTCPport = 7777;
    public static final String serverIP = "192.168.199.137";
    public static final int poolMaxSize = 64;
    public static final int connectMaxSize = 32;
    private final List<userdata> ud = new ArrayList<>();
    private static ExecutorService pool;

    public static void main(String[] arg) {
        pool = Executors.newFixedThreadPool(poolMaxSize);
        System.out.println("Server Start");
        new server().ServerStart();
    }

    public void ServerStart() {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(serverTCPport);
        } catch (IOException ex) {
        }
        while (ss != null) {
            Socket s;
            try {
                s = ss.accept();
                Thread t = new Thread(new recive(s));
                pool.execute(t);
            } catch (IOException ex) {
            }
        }
    }

    private class recive implements Runnable {

        byte[] dataRecived = new byte[1024];
        Socket s;

        recive(Socket socket) {
            s = socket;
        }

        @Override
        public void run() {
            try {
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                DataInputStream dis = new DataInputStream(s.getInputStream());
                BufferedReader br = new BufferedReader(new InputStreamReader(dis));
                dos.write("OK\n".getBytes());
                String msg = br.readLine();
                userdata uda = null;
                if ("CONNECT".equals(msg)) {
                    if (ud.size() < connectMaxSize) {
                        uda = new userdata(s.getInetAddress().toString(), s.getPort());
                        ud.add(uda);
                        System.out.println("当前在线人数:" + ud.size());
                        dos.write("ACCEPT\n".getBytes());
                        System.out.println("连接:" + s.getInetAddress() + ":" + s.getPort() + ":" + msg);
                    } else {
                        dos.write("FULL".getBytes());
                        System.out.println("连接池已满");
                    }
                }
                while (true) {
                    try {
                        msg = br.readLine();
                        System.out.println("收到消息： " + msg);
                        String[] temp = msg.split(" ");
                        switch (temp[0]) {
                            case "ADD":
//                                Session session = new HibernateUtil().getSession();
//                                Transaction ta = session.getTransaction();
//                                FILELIST fl = new FILELIST();
//                                try {
//                                    session.save(s);
//                                    ta.commit();
//                                } catch (Exception e) {
//                                    ta.rollback();
//                                } finally {
//                                    session.close();
//                                }
                                
                                System.out.println(uda.ip + " 成功添加文件：" + temp[1] + " hash: " + temp[2] + " 大小：" + temp[3] + "B");
                                dos.write("OK\n".getBytes());
                                break;
                            case "DELETE":
                                //int stat = db.delete(temp[1], temp[2], s.getInetAddress().toString());
                                int stat = 1;
                                if (stat == 0) {
                                    dos.write("OK\n".getBytes());
                                    System.out.println("删除成功");
                                } else if (stat == 1) {
                                    dos.write("Invalue user\n".getBytes());
                                    System.out.println("没有删除权限");
                                } else {
                                    dos.write("No such file\n".getBytes());
                                    System.out.println("没有找到该文件");
                                }
                                break;
                            case "LIST":
//                                String[] list = db.list();
//                                for (int i = 0; i < list.length; i += 2) {
//                                    dos.write((list[i] + " " + list[i + 1] + "\n").getBytes());
//                                }
//                                dos.write("OK\n".getBytes());
//                                System.out.println("查询成功");
//                                break;
                            case "QUIT":
                                ud.remove(uda);
                                System.out.println("断开连接:" + uda.ip + ":" + uda.port);
                                System.out.println("当前在线人数:" + ud.size());
                                dos.write("GOODBYE\n".getBytes());
                                s.close();
                                return;
                            case "REQUEST":
//                                String[] re = db.find(temp[1]);
//                                if (re != null && re[0] != null && !"".equals(re[0])) {
//                                    dos.write((re[0].replace("/", "") + " " + re[1] + "\n").getBytes());
//                                    System.out.println("查找成功");
//                                } else {
//                                    System.out.println("查找失败");
//                                    dos.write("ERROR\n".getBytes());
//                                }
//                                break;
                            default:
                                System.out.println("不支持指令");
                                break;
                        }
                    } catch (IOException ex) {
                    }
                }
            } catch (IOException ex) {
            }
        }
    }

    private class userdata {

        private final String ip;
        private final int port;

        userdata(String i, int p) {
            ip = i;
            port = p;
        }
    }
}
